package com.lhr.common.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;

public class StringUtil {

	/**
	 * 替换占位符
	 */
	public static String replacePlaceholder(String content,
			Object... vals) {
		if (ValidateUtil.isEmpty(vals))
			return content;

		for (Object val : vals) {
			content = StringUtils.replaceOnce(content, "{}", String.valueOf(val));
		}
		return content;
	}

	public static String merge(Object... values) {
		return merge(null, values).toString();
	}

	public static StringBuffer merge(StringBuffer buffer,
			Object... values) {
		return merge(buffer, null, false, values);
	}

	/**
	 * 
	 * @param values
	 * @param buffer
	 * @param separator
	 *            分割符
	 * @param isAppendSepToTail
	 *            分割符是否追加
	 */
	public static StringBuffer merge(StringBuffer buffer,
			String separator,
			boolean isAppendSepToTail,
			Object... values) {

		if (ValidateUtil.isEmpty(values))
			return null;

		if (buffer == null)
			buffer = new StringBuffer();

		for (int i = 0; i < values.length; i++) {
			buffer.append(values[i]);
			if (separator == null)
				continue;
			boolean isTail = isAppendSepToTail ? true : i < (values.length - 1);
			if (isTail)
				buffer.append(separator);
		}
		return buffer;
	}

	public static String buildGetMethod(String fieldName) {
		return merge("get", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1));
	}

	public static String buildSetMethod(String fieldName) {
		return merge("set", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1));
	}

	public static String decodeUTF8(String val) {
		try {
			return java.net.URLDecoder.decode(val, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String encodeUTF8(String val) {
		try {
			return java.net.URLEncoder.encode(val, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
